class ClockLearningGame {
    constructor() {
        this.currentTime = { hours: 12, minutes: 0, seconds: 0 };
        this.isRealTime = false;
        this.practiceMode = false;
        this.quizMode = false;
        this.targetTime = null;
        this.quizQuestions = [];
        this.currentQuizIndex = 0;
        
        this.initializeElements();
        this.bindEvents();
        this.updateClock();
        this.startRealTime();
    }

    initializeElements() {
        this.hourHand = document.getElementById('hour-hand');
        this.minuteHand = document.getElementById('minute-hand');
        this.secondHand = document.getElementById('second-hand');
        this.digitalTime = document.getElementById('digital-time');
        this.timeText = document.getElementById('time-text');
        this.hourInput = document.getElementById('hour-input');
        this.minuteInput = document.getElementById('minute-input');
        this.secondInput = document.getElementById('second-input');
        this.setTimeBtn = document.getElementById('set-time-btn');
        this.realTimeBtn = document.getElementById('real-time-btn');
        this.randomTimeBtn = document.getElementById('random-time-btn');
        this.resetBtn = document.getElementById('reset-btn');
        this.practiceModeBtn = document.getElementById('practice-mode-btn');
        this.quizModeBtn = document.getElementById('quiz-mode-btn');
        this.practicePanel = document.getElementById('practice-panel');
        this.quizPanel = document.getElementById('quiz-panel');
        this.targetTimeSpan = document.getElementById('target-time');
        this.practiceResult = document.getElementById('practice-result');
        this.quizOptions = document.getElementById('quiz-options');
        this.quizResult = document.getElementById('quiz-result');
        this.checkAnswerBtn = document.getElementById('check-answer-btn');
        this.nextQuestionBtn = document.getElementById('next-question-btn');
        this.exitPracticeBtn = document.getElementById('exit-practice-btn');
        this.exitQuizBtn = document.getElementById('exit-quiz-btn');
    }

    bindEvents() {
        this.setTimeBtn.addEventListener('click', () => this.setCustomTime());
        this.realTimeBtn.addEventListener('click', () => this.toggleRealTime());
        this.randomTimeBtn.addEventListener('click', () => this.setRandomTime());
        this.resetBtn.addEventListener('click', () => this.resetClock());
        this.practiceModeBtn.addEventListener('click', () => this.startPracticeMode());
        this.quizModeBtn.addEventListener('click', () => this.startQuizMode());
        this.checkAnswerBtn.addEventListener('click', () => this.checkPracticeAnswer());
        this.nextQuestionBtn.addEventListener('click', () => this.nextPracticeQuestion());
        this.exitPracticeBtn.addEventListener('click', () => this.exitPracticeMode());
        this.exitQuizBtn.addEventListener('click', () => this.exitQuizMode());
        
        this.hourInput.addEventListener('input', () => this.validateInput(this.hourInput, 0, 23));
        this.minuteInput.addEventListener('input', () => this.validateInput(this.minuteInput, 0, 59));
        this.secondInput.addEventListener('input', () => this.validateInput(this.secondInput, 0, 59));
    }

    validateInput(input, min, max) {
        let value = parseInt(input.value) || 0;
        if (value < min) input.value = min;
        if (value > max) input.value = max;
    }

    updateClock() {
        const { hours, minutes, seconds } = this.currentTime;
        
        const hourAngle = (hours % 12) * 30 + minutes * 0.5;
        const minuteAngle = minutes * 6;
        const secondAngle = seconds * 6;
        
        this.hourHand.style.transform = `translateX(-50%) rotate(${hourAngle}deg)`;
        this.minuteHand.style.transform = `translateX(-50%) rotate(${minuteAngle}deg)`;
        this.secondHand.style.transform = `translateX(-50%) rotate(${secondAngle}deg)`;
        
        const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        this.digitalTime.textContent = timeString;
        
        this.timeText.textContent = this.getTimeText(hours, minutes);
    }

    getTimeText(hours, minutes) {
        const hourNames = ['十二', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
        const minuteNames = ['整', '零五分', '十分', '十五分', '二十分', '二十五分', '三十分', '三十五分', '四十分', '四十五分', '五十分', '五十五分'];
        
        let timeText = '';
        
        if (hours >= 0 && hours < 12) {
            timeText = '上午';
        } else if (hours >= 12 && hours < 18) {
            timeText = '下午';
        } else {
            timeText = '晚上';
        }
        
        const displayHour = hours % 12 || 12;
        const minuteIndex = Math.floor(minutes / 5);
        
        timeText += hourNames[displayHour] + '点' + minuteNames[minuteIndex];
        
        return timeText;
    }

    setCustomTime() {
        const hours = parseInt(this.hourInput.value) || 0;
        const minutes = parseInt(this.minuteInput.value) || 0;
        const seconds = parseInt(this.secondInput.value) || 0;
        
        this.currentTime = { hours, minutes, seconds };
        this.isRealTime = false;
        this.updateClock();
        this.updateInputs();
        this.addSuccessAnimation();
    }

    toggleRealTime() {
        this.isRealTime = !this.isRealTime;
        this.realTimeBtn.textContent = this.isRealTime ? '⏸️ 暂停实时' : '🕐 显示当前时间';
        
        if (this.isRealTime) {
            this.startRealTime();
        } else {
            this.stopRealTime();
        }
    }

    startRealTime() {
        if (this.realTimeInterval) {
            clearInterval(this.realTimeInterval);
        }
        
        this.realTimeInterval = setInterval(() => {
            if (this.isRealTime) {
                const now = new Date();
                this.currentTime = {
                    hours: now.getHours(),
                    minutes: now.getMinutes(),
                    seconds: now.getSeconds()
                };
                this.updateClock();
                this.updateInputs();
            }
        }, 1000);
    }

    stopRealTime() {
        if (this.realTimeInterval) {
            clearInterval(this.realTimeInterval);
            this.realTimeInterval = null;
        }
    }

    setRandomTime() {
        const hours = Math.floor(Math.random() * 24);
        const minutes = Math.floor(Math.random() * 60);
        const seconds = Math.floor(Math.random() * 60);
        
        this.currentTime = { hours, minutes, seconds };
        this.isRealTime = false;
        this.updateClock();
        this.updateInputs();
        this.addSuccessAnimation();
    }

    resetClock() {
        this.currentTime = { hours: 12, minutes: 0, seconds: 0 };
        this.isRealTime = false;
        this.updateClock();
        this.updateInputs();
        this.addSuccessAnimation();
    }

    updateInputs() {
        this.hourInput.value = this.currentTime.hours;
        this.minuteInput.value = this.currentTime.minutes;
        this.secondInput.value = this.currentTime.seconds;
    }

    addSuccessAnimation() {
        const clock = document.querySelector('.clock');
        clock.classList.add('success-animation');
        setTimeout(() => {
            clock.classList.remove('success-animation');
        }, 500);
    }

    startPracticeMode() {
        this.practiceMode = true;
        this.quizMode = false;
        this.practicePanel.style.display = 'block';
        this.quizPanel.style.display = 'none';
        this.generatePracticeQuestion();
    }

    generatePracticeQuestion() {
        const hours = Math.floor(Math.random() * 12) + 1;
        const minutes = Math.floor(Math.random() * 12) * 5;
        
        this.targetTime = { hours, minutes, seconds: 0 };
        this.targetTimeSpan.textContent = `${hours}:${minutes.toString().padStart(2, '0')}`;
        
        this.currentTime = { hours: 12, minutes: 0, seconds: 0 };
        this.updateClock();
        this.updateInputs();
        
        this.practiceResult.textContent = '';
        this.practiceResult.className = 'practice-result';
    }

    checkPracticeAnswer() {
        const isCorrect = 
            this.currentTime.hours === this.targetTime.hours &&
            this.currentTime.minutes === this.targetTime.minutes;
        
        if (isCorrect) {
            this.practiceResult.textContent = '🎉 太棒了！答对了！';
            this.practiceResult.className = 'practice-result correct';
            this.addSuccessAnimation();
        } else {
            this.practiceResult.textContent = `❌ 不对哦！正确答案是 ${this.targetTime.hours}:${this.targetTime.minutes.toString().padStart(2, '0')}`;
            this.practiceResult.className = 'practice-result incorrect';
        }
    }

    nextPracticeQuestion() {
        this.generatePracticeQuestion();
    }

    exitPracticeMode() {
        this.practiceMode = false;
        this.practicePanel.style.display = 'none';
        this.resetClock();
    }

    startQuizMode() {
        this.quizMode = true;
        this.practiceMode = false;
        this.quizPanel.style.display = 'block';
        this.practicePanel.style.display = 'none';
        this.generateQuizQuestion();
    }

    generateQuizQuestion() {
        const hours = Math.floor(Math.random() * 12) + 1;
        const minutes = Math.floor(Math.random() * 12) * 5;
        
        this.currentTime = { hours, minutes, seconds: 0 };
        this.updateClock();
        this.updateInputs();
        
        const correctAnswer = `${hours}:${minutes.toString().padStart(2, '0')}`;
        const options = [correctAnswer];
        
        while (options.length < 4) {
            const wrongHours = Math.floor(Math.random() * 12) + 1;
            const wrongMinutes = Math.floor(Math.random() * 12) * 5;
            const wrongAnswer = `${wrongHours}:${wrongMinutes.toString().padStart(2, '0')}`;
            
            if (!options.includes(wrongAnswer)) {
                options.push(wrongAnswer);
            }
        }
        
        this.shuffleArray(options);
        
        this.quizOptions.innerHTML = '';
        options.forEach((option, index) => {
            const optionDiv = document.createElement('div');
            optionDiv.className = 'quiz-option';
            optionDiv.textContent = option;
            optionDiv.addEventListener('click', () => this.selectQuizOption(optionDiv, option, correctAnswer));
            this.quizOptions.appendChild(optionDiv);
        });
        
        this.quizResult.textContent = '';
    }

    selectQuizOption(optionElement, selectedAnswer, correctAnswer) {
        document.querySelectorAll('.quiz-option').forEach(opt => {
            opt.classList.remove('selected');
        });
        
        optionElement.classList.add('selected');
        
        if (selectedAnswer === correctAnswer) {
            optionElement.classList.add('correct');
            this.quizResult.textContent = '🎉 答对了！';
            this.quizResult.className = 'quiz-result correct';
            this.addSuccessAnimation();
        } else {
            optionElement.classList.add('incorrect');
            this.quizResult.textContent = `❌ 不对哦！正确答案是 ${correctAnswer}`;
            this.quizResult.className = 'quiz-result incorrect';
        }
    }

    shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }

    exitQuizMode() {
        this.quizMode = false;
        this.quizPanel.style.display = 'none';
        this.resetClock();
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new ClockLearningGame();
});
